package com.bs.manager04.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.bs.manager04.entity.Menu;
import com.bs.manager04.entity.Role;
import com.bs.manager04.entity.User;
import com.bs.manager04.service.IMenuService;
import com.bs.manager04.service.IRoleService;
import com.bs.manager04.service.IUserService;
import com.bs.manager04.service.IUserroleService;
import com.bs.manager04.utils.*;
import com.bs.manager04.utils.auth.Auth;
import com.bs.manager04.utils.exception.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * <p>
 * 用户信息表 前端控制器
 * </p>
 *
 * @author yao
 * @since 2022-12-17
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户管理表")
public class UserController {
    @Resource
    IUserService service;

    @Resource
    IUserroleService service1;
    //固定盐
    private String slat="baisi";

    @Resource
    IRoleService service2;

    @Resource
    RedisUtils utils;

    @Resource
    IMenuService service3;


    @GetMapping
    @ApiOperation("用户分页条件查询")
    @Auth("system:user")
    @PreAuthorize("@auth.hasAuth('system:user')")
    public Result getIndexMenu(@ApiParam("当前页") @RequestParam(defaultValue = "1") Integer pageNum, @ApiParam("页面大小") @RequestParam(defaultValue = "5") Integer pageSize, @ApiParam("用户名")  @RequestParam(defaultValue = "") String name){
        Page<User> page = new Page<>(pageNum,pageSize);
        LambdaQueryWrapper<User> lq=new LambdaQueryWrapper<>();
        lq.like(StringUtils.isNotBlank(name),User::getUsername,name);
        page=service.page(page,lq);
        return Result.success(page);
    }


    @PostMapping
    @ApiOperation("用户添加")
    public Result addMenu(@ApiParam("用户表")@RequestBody User menu){
        menu.setPassword(MD5SaltUtils.password(menu.getPassword(),slat));
        boolean save = service.save(menu);
        if(save){
            return Result.success("添加用户信息成功");
        }else{
            return Result.fail("添加用户信息失败");
        }
    }


    @GetMapping("/{id}")
    @ApiOperation("根据用户id查询用户列表")
    @Auth("system:user")
    public Result getByMenuID(@PathVariable("id") @ApiParam("用户id") String id){
        User menu = service.getById(id);
        return Result.success(menu);
    }


    @PutMapping
    @ApiOperation("用户修改")
    @Auth("system:user:update")
    public Result updateMenu(@RequestBody @ApiParam("用户表") User menu){
        boolean save = service.updateById(menu);
        if(save){
            return Result.success("修改用户信息成功");
        }else{
            return Result.fail("修改用户信息失败");
        }
    }

    @DeleteMapping("/{id}")
    @ApiOperation("用户删除")
    @Auth("system:user:del")
    public Result delMenu(@PathVariable("id") @ApiParam("用户id") String id){
        boolean del = service.removeById(id);
        if(del){
            return Result.success("删除用户信息成功");
        }else{
            return Result.fail("删除用户信息失败");
        }
    }

    //给用户添加对应的角色
    @PutMapping("/addRoles")
    @ApiOperation("给用户添加对应的角色")
    public Result addRoles(@ApiParam("用户id") @RequestParam String userid,@ApiParam("角色id") @RequestParam String[] roleids){
        int row = service1.addRoles(userid, roleids);
        if(row>0){
            return Result.success("成功");
        }
        return Result.fail("失败");
    }

   /* //登录
    @PostMapping("/login")
    @ApiOperation("用户登录")
    public Result login(@ApiParam("用户名") @RequestParam String username,@ApiParam("用户密码")  @RequestParam String pwd, HttpServletRequest request){
        //获取session对象
        HttpSession session = request.getSession();
        //判断用户名是否为空
        if(StringUtils.isNotBlank(username)){
            LambdaQueryWrapper<User> lq=new LambdaQueryWrapper<>();
            lq.eq(User::getUsername,username);
            User user = service.getOne(lq);
            //判断用户对应是否存在
            if(user!=null){
                 //判断用户密码是否为空
                if(StringUtils.isNotBlank(pwd)){
                     //判断用户密码是否正确

                    if(MD5SaltUtils.equals(pwd,slat,user.getPwd())){
                           if(user.getStatus()==1){
                               throw new StatusException("该用户已被冻结");
                           }else if(user.getStatus()==2){
                               throw new StatusException("该用户已被注销");
                           }
                           //用户登录成功后,展示以树形结构的菜单列表
                        //根据用户id，查询该用户所对应的角色
                        List<Role> roles = service2.addRoles(user.getUserid());
                           user.setRoles(roles);
                        //根据用户id，查询该用户的菜单列表
                        List<Menu> menus = service3.addMenus(user.getUserid(), "0");
                         user.setMenus(menus);
                        //查询该用户所对应的菜单权限
                        List<String> premission = service3.addPremission(user.getUserid());
                        Set<String> sets=new HashSet<>(premission);
                        user.setPremission(sets);
                        //登录成功，将用户对象放到session中
                        String token = UUIDFactory.UUID();
                        //如果一个用户访问多个服务器，如果使用session进行存储，因为session不能实现分布式，所以系统会为每个
                        //服务器创建一个sessionid，这样会导致浪费太多的资源，所以我们将数据存在redis中，可以实现分布式，还可以
                        //设置失效时间
                        utils.set(token,user, TokenUtils.TOKEN_TIME);
                        Map<String,Object> map=new HashMap<>();
                        map.put("token",token);
                        map.put("user",user);
                        return Result.success(map);
                    }else{
                        throw new PasswordEqualException("用户密码不正确");
                    }
                }else{
                    throw new PassWordNullException("用户密码不能为空");
                }
            }else{
                throw new NotUserException("用户信息不存在");
            }

        }else{
            throw new NotUserNullException("用户名不存在");
        }
    }*/

    @PostMapping("/login")
    public Result login(@RequestBody User user){
        String token = service.login(user);
        return Result.success(token);
    }

    @GetMapping("/getUsers")
    public Result getUsers(HttpServletRequest request){
        //获取请求消息头数据
        String token = request.getHeader(TokenUtils.TOKEN_NAME);
        //通过获取的token标识,获取存放在redis中的用户信息
        User user =(User) utils.get(token);
        if(user!=null){
         return Result.success(user);
        }else{
            return Result.fail("用户未登录");
        }
    }

    //退出登录
    @GetMapping("/edit")
    public Result loginOut(){
        service.loginout();
        return Result.success("退出成功");
    }

}

